// axios  : 目前 使用最多的 ajax 请求库；一个ajax 框架 底层是通过xmlhttprequest 封装的； 就是用于发送ajax 的；
// 官网 ； https://www.axios-http.cn/
// 既可以用于 前端  也可以用于nodejs端；
const express = require("express");
const bodyParser = require("body-parser");
const userModel = require("./models/usermodel");
const { model } = require("mongoose");
const static = express.static;
let app = express();
app.use(bodyParser.urlencoded({
    extended:false
}))
app.use(bodyParser.json())
app.use(static(__dirname+"/static"));
app.get("/",(req,res)=>{
    res.sendFile(__dirname+"/views/index.html");
})



app.get("/getdata",async (req,res)=>{
    try {
        let result = await userModel.find();
        res.json({
          info: "获取成功",
          status: 1,
          result,
        });
      } catch (err) {
        res.json({
          info: "获取失败",
          status: 0,
        });
      }
})

app.post("/adddata", async(req,res)=>{
    console.log(req.body);
  await userModel.create(req.body);
  res.json({
    info: "添加成功",
    status: 1,
  });
})


app.get("/delUser", async (req, res) => {
    try {
      let { _id } = req.query;
      let result = await userModel.deleteOne({ _id });
      console.log(_id, result);
      res.json({ info: "删除成功", status: 1 });
    } catch (err) {
      res.json({ info: "删除失败", status: 0 });
    }
  });



  app.get("/replydata", async (req, res) => {
    try {
      console.log(req.query);
      let { _id, inputval } = req.query;
      let [{ replay }] = await userModel.find({ _id: _id });
      console.log("2222", replay);
      replay.push(inputval);
      await userModel.updateOne({ _id: _id }, { $set: { replay: replay } });
      res.json({ info: "回复添加成功", status: 1 });
    } catch (err) {
      res.json({ info: "回复添加失败", status: 0 });
      console.log(err);
    }
  });
app.listen(9999);